/*
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#ifndef _AUTO_UPDATE_H_
#define _AUTO_UPDATE_H_

#pragma once

#include "..\client\Singleton.h"
#include "..\client\Semaphore.h"
#include "..\client\SettingsManager.h"
#include "..\client\TimerManager.h"
#include "..\XMLParser\xmlParser.h"

// [+] SSA
#define UPDATE_FILE_NAME "viewlink.upd" 

#define UPDATE_RELEASE_URL ""
#define UPDATE_BETA_URL ""

#define WM_AUTO_UPDATE_RESTART WM_USER + 2

class AutoUpdateGUIMethod {
public:
	virtual ~AutoUpdateGUIMethod() { };
	virtual UINT ShowDialogUpdate(std::string message, std::string rtfMessage) { return 0; };
};

class AutoUpdateListener {
public:
	virtual ~AutoUpdateListener() { }
	template<int I>	struct X { enum { TYPE = I };  };

	typedef X<0> UpdateStarted;
	typedef X<1> Failed;

	virtual void on(UpdateStarted, const string&) throw() { }
    virtual void on(Failed, const string&) throw() { }
}; 


class AutoUpdateFile
{
public:
	enum OpSystem
	{
		xALL = 0,
		x86,
		x64,
		OsUnknown
	};
	enum Packers
	{
		Unpacked = 0,
		BZip2,
		Zip,
		PackUnknown
	};
	string m_sName;
	string m_sPath;
	OpSystem m_sys;
	Packers  m_packer;
	int64_t	 m_size;
	int64_t  m_packedSize;
	string m_sTTH;
	string m_sDownloadURL;

};

typedef std::vector<AutoUpdateFile> AutoUpdateFiles;


class AutoUpdateModule
{
public:
	string m_sName;
	SettingsManager::IntSetting	   m_iSetting;
	AutoUpdateFiles m_Files;
};

typedef std::vector<AutoUpdateModule> AutoUpdateModules;

class AutoUpdateObject{
public:
	string m_sVersion;
	string m_sUpdateDate;
	AutoUpdateModules m_Modules;
	AutoUpdateModule m_updater;
};


class AutoUpdate : 
    public Singleton<AutoUpdate>, public Speaker<AutoUpdateListener>, public Thread, private SettingsManagerListener, private TimerManagerListener
{

public:

	void initialize(HWND mainFrameHWND, AutoUpdateGUIMethod* guiDelegate);
	void StartUpdate(bool p_manualUpdate = false);
	bool IsUpdateStarted() { return isUpdateStarted; }
	void shutdown();

	enum UpdateResult{
		UPDATE_NOW = 0,
		UPDATE_IGNORE,
		UPDATE_CANCEL, // next time
	};


private:
	bool isUpdateStarted;
	HWND _mainFrameHWND;
	AutoUpdateGUIMethod* m_guiDelegate;
	bool m_manualUpdate;

	friend class Singleton<AutoUpdate>;

	AutoUpdate():isUpdateStarted(false),failed(false) { start(); } 

	virtual ~AutoUpdate() throw();

    // SettingsManagerListener
	virtual void on(SettingsManagerListener::Save, SimpleXML& xml) throw() {
		// load();
	}

	enum Tasks {
		START_UPDATE,
		STOP_UPDATE,
		SHUTDOWN
	};


    struct TaskData { 
		virtual ~TaskData() throw() { }
	};

    CriticalSection cs;
    Semaphore taskSem;

	list<pair<Tasks, TaskData*> > m_tasks;
	int run();

	bool failed;

	void fail(const string& aError);	
	bool checkEvents();


	void addTask(Tasks task, TaskData* data) 
	{
	     m_tasks.push_back(make_pair(task, data)); 
		 taskSem.signal(); 
	}

	virtual void on(TimerManagerListener::Minute, uint64_t aTick) throw();

	void startUpdateThisThread();

	SettingsManager::IntSetting GetSettingByTitle(const wstring& wTitle);
	bool NeedUpdateFile(AutoUpdateFile& file, const string& outputFolder);
	bool PrepareFile(AutoUpdateFile& file, const string& tempFolder);
	string GetTempFolderForUpdate(const string &version);
	bool verifyUpdate(byte* signData, size_t& signDataSize, string& data, size_t& dataSize);

	std::string UPDATE_FILEDOWNLOAD();
	std::string UPDATE_SIGNFILEDOWNLOAD();
	std::string UPDATE_DESCRIPTION();
	std::string getAUTOUPDATE_SERVER_URL();
	AutoUpdateFile ParseNode(XMLParser::XMLNode& Node);
};

#endif // _AUTO_UPDATE_H_

